package com.open.rbac.config;

import java.util.Optional;

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.lang.NonNull;
import org.springframework.security.core.context.SecurityContextHolder;

import com.open.rbac.config.security.MeUsernamePasswordAuthenticationToken;

/**
 * 审计
 *
 * @author Riche's
 * @since 2024/11/11
 */
@Slf4j
@Configuration
public class MeAuditorAware implements AuditorAware<String> {

    @NonNull
    @Override
    public Optional<String> getCurrentAuditor() {
        String userId = "0";
        // 从Jwt、Spring Security上下文中获取用户Id
        MeUsernamePasswordAuthenticationToken token =
                (MeUsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        if (token != null) {
            userId = token.getId();
        }
        log.info("从Jwt、Spring Security上下文中获取用户Id： {}", userId);
        return Optional.of(userId);
    }
}
